package com.hofon.medical.dynamicdb;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.alibaba.fastjson.JSON;

/**
 * 测试下db变化事件是否可以在spring容器中获取
 * @author kongxiangyi
 *
 */
public class DbChangedEventTrigger {
    private static Logger log = LoggerFactory.getLogger(DbChangedEventTrigger.class);
    public static void main(String[] args) throws SQLException {
        //这是通过配置文件new一个spring容器
        ApplicationContext app = new ClassPathXmlApplicationContext(
                "classpath:META-INF/spring/service-impl-context.xml");

        //这是通过bean获取spring容器，在实际项目中会用这种方式获取
        DynamicDataSourceListener dl = (DynamicDataSourceListener)app.getBean("dynamicDataSourceListener");
        ApplicationContext app1 =dl.getApplicationContext();
        String dpn = app1.getDisplayName();
        String id = app1.getId();
        log.info(dpn);
        log.info(id);

        //检验2种方式获取到的容器是否一样
        log.debug(app.toString());
        log.debug(app1.toString());

        //如果变化成功，就可以直接通过bean获取新的数据源（查看日志可见）
        app1.publishEvent(new DbChangedEvent(app1));
        Object o = app1.getBean("his2.hospital_1");
        BasicDataSource bds = (BasicDataSource)o;
        Connection c = bds.getConnection();
        Properties p = c.getClientInfo();
        String s = JSON.toJSONString(p);
        log.info(s);
    }
}
